#include "patientselectdialog.h"
#include "ui_patientselectdialog.h"

#include <QMessageBox>
#include <QSqlDatabase>
#include <QSqlRecord>
#include <QSqlQueryModel>

PatientSelectDialog::PatientSelectDialog(const QString &name, QWidget *parent) :
    m(new QSqlQueryModel(this)),
    QDialog(parent),
    ui(new Ui::PatientSelectDialog)
{
    ui->setupUi(this);

    ui->studyView->setModel(m);
    m->setQuery("SELECT pati_id, pati_name, pati_sex, pati_birth, pati_adid, pati_alert FROM study_t WHERE pati_name LIKE \'%" + name + "%\'", QSqlDatabase::database());
    m->setHeaderData(0, Qt::Horizontal, tr("Patient Id"));
    m->setHeaderData(1, Qt::Horizontal, tr("Name"));
    m->setHeaderData(2, Qt::Horizontal, tr("Sex"));
    m->setHeaderData(3, Qt::Horizontal, tr("Birth"));
    m->setHeaderData(4, Qt::Horizontal, tr("Admission Id"));
    m->setHeaderData(5, Qt::Horizontal, tr("Alert"));

    //ui->patientTableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
    ui->studyView->selectRow(0);
    connect(ui->selectButton, SIGNAL(clicked()), this, SLOT(onSelect()));
    connect(ui->studyView, SIGNAL(activated(QModelIndex)), this, SLOT(onItemActivated(QModelIndex)));
}

PatientSelectDialog::~PatientSelectDialog()
{
    delete ui;
}

void PatientSelectDialog::onSelect()
{
    onItemActivated(ui->studyView->currentIndex());
}

void PatientSelectDialog::onItemActivated(const QModelIndex &index)
{
    if (index.isValid()) {
        study = m->record(index.row());
        accept();
    } else {
        QMessageBox::warning(this, tr("Patient Select"),
                             tr("Select one patient first."));
    }
}
